/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.controller.evaluation.analyze.correction;

import cn.ac.nercis.pes.common.constant.project.FinishState;
import cn.ac.nercis.pes.common.utils.ConvertUtils;
import cn.ac.nercis.pes.community.component.dialog.MessageDialog;
import cn.ac.nercis.pes.community.component.dialog.MessageType;
import cn.ac.nercis.pes.community.component.dialog.PageDialog;
import cn.ac.nercis.pes.community.component.spreadsheet.analyze.EvalCorrectionSheetView;
import cn.ac.nercis.pes.community.controller.base.GlobalEventHandle;
import cn.ac.nercis.pes.community.controller.evaluation.analyze.ResultCorrectionController;
import cn.ac.nercis.pes.community.manager.RealTimeSaveManager;
import cn.ac.nercis.pes.community.mapper.evaluation.ResultCorrectionViewMapper;
import cn.ac.nercis.pes.community.model.vo.MenuVO;
import cn.ac.nercis.pes.community.model.vo.evaluation.ResultCorrectionVO;
import cn.ac.nercis.pes.community.utils.*;
import cn.ac.nercis.pes.community.views.evaluation.analyze.ResultCorrectionView;
import cn.ac.nercis.pes.community.views.evaluation.analyze.correction.OffsetAssetView;
import cn.ac.nercis.pes.model.dto.evaluation.analyze.OffsetAssetDTO;
import cn.ac.nercis.pes.model.dto.evaluation.analyze.ResultCorrectionDTO;
import cn.ac.nercis.pes.service.evaluation.ResultCorrectionService;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.net.URL;
import java.util.List;
import java.util.Objects;
import java.util.ResourceBundle;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;

/**
 * 测评对象结果修正管理控制器
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
public class EvalCorrectionController implements Initializable, GlobalEventHandle {

    @FXML
    private VBox evalCorrectionBox;
    @FXML
    private AnchorPane emptyPane;
    @FXML
    private ImageView emptyImageView;
    @FXML
    private Label emptyLabel;

    @FXML
    private Label titleLbl;
    @FXML
    private Button tmpSaveButton;
    @FXML
    private Button saveButton;

    @FXML
    private EvalCorrectionSheetView sheetView;

    private final ResultCorrectionService resultCorrectionService;

    private final ExecutorService executor;
    private final RealTimeSaveManager realTimeSaveManager = new RealTimeSaveManager(this::realTimeSave);

    private MenuVO currentLayerTarget;

    private PageDialog pageDialog;
    private StackPane page;
    private String currentSystemId;

    public EvalCorrectionController() {
        this.resultCorrectionService = SpringUtils.getBean(ResultCorrectionService.class);
        this.executor = SpringUtils.getBean(ExecutorService.class);
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        saveButton.setGraphic(IconUtils.getGlyph("save-button-icon", "btn-icon"));
        tmpSaveButton.setGraphic(IconUtils.getGlyph("temp-save-button-icon", "btn-icon"));

        ControlUtils.initEmptyImageView(this.emptyImageView,log);
        GuiStore.applyQuickSave(this.evalCorrectionBox,this::onGlobalSave);
        realTimeSaveManager.listenerSheetChange(this.sheetView);
    }

    public void initializeData(String systemId,MenuVO layerTarget,StackPane page){
        LogUtils.info(log, "初始化测评对象结果修正信息...");
        this.currentSystemId = systemId;
        this.page = page;
        this.currentLayerTarget = layerTarget;
        this.titleLbl.setText(this.currentLayerTarget.getTitle());
        this.sheetView.initialize(this::onOptionClick);
        queryCorrectionList();
    }

    @Override
    public void onGlobalSave() {
        LogUtils.info(log, "执行快捷保存操作...");
        batchSaveCorrection(false,false);
    }

    @FXML
    public void onTmpSave(){
        LogUtils.info(log, "执行暂存操作...");
        batchSaveCorrection(false,false);
    }

    @FXML
    public void onFinishSave(){
        LogUtils.info(log, "执行保存操作...");
        batchSaveCorrection(false,true);
    }

    public void realTimeSave(){
        LogUtils.info(log, "执行即时保存操作...");
        batchSaveCorrection(true, false);
    }

    public void onOptionClick(ResultCorrectionVO correction){
        LogUtils.info(log, "选择弥补对象操作...");
        selectOffsetAsset(correction);
    }

    private void selectOffsetAsset(ResultCorrectionVO current) {
        var assetView = AppStore.getEvaluationView(this.currentSystemId, OffsetAssetView.class);
        pageDialog = PageDialog.builder()
                .withIcon("dialog-edit-icon")
                .withTitle("选择弥补对象")
                .withContent(Objects.requireNonNull(assetView).load())
                .withOwner(AppStore.getCurrentSystem(this.currentSystemId).getEvaluationStage())
                .build();
        pageDialog.setYesText("确定");
        pageDialog.setNoText("取消");
        if(assetView.getController() instanceof OffsetAssetController controller){
            controller.initializeData(current);
            controller.setDelOffsetAsset(()->this.removeOffsetAsset(current));
        }
        pageDialog.show(()->applyOffsetAsset(current));
    }

    private void applyOffsetAsset(ResultCorrectionVO current) {
        var assetView = AppStore.getEvaluationView(this.currentSystemId, OffsetAssetView.class);
        if(assetView.getController() instanceof OffsetAssetController controller){
            OffsetAssetDTO offsetAsset = controller.getSelected();
            if (Objects.nonNull(offsetAsset)) {
                current.setOffsetRecordId(offsetAsset.getRecordId());
                current.setOffsetAssetName(offsetAsset.getAssetName());
                pageDialog.close();
                refreshOffsetAsset(current);
            }
        }
    }

    private void removeOffsetAsset(ResultCorrectionVO current) {
        current.setOffsetRecordId(StringUtils.EMPTY);
        current.setOffsetAssetName(StringUtils.EMPTY);
        pageDialog.close();
        refreshOffsetAsset(current);
    }

    private void refreshOffsetAsset(ResultCorrectionVO current){
        LogUtils.info(log, "计算测评对象结果修正信息...");
        LogUtils.record(log, "请求数据:{}", current);
        CompletableFuture.supplyAsync(() -> this.resultCorrectionService.computerResultCorrection(ResultCorrectionViewMapper.INSTANCE.toDTO(current)),this.executor)
                .thenAccept(res -> Platform.runLater(() -> {
                    if (!res.isSuccess()) {
                        MessageDialog.builder()
                                .withContainer(this.page)
                                .withType(MessageType.FAIL)
                                .withMessage(res.getMsg())
                                .build().show();
                    } else {
                        current.setResult(res.getData().getResult());
                        current.setScore(ConvertUtils.scoreToString(res.getData().getScore(), ""));
                        this.sheetView.refreshOffsetAssetInfo(current);
                        this.realTimeSave();
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("计算测评对象结果修正信息出错!", ex);
                    return null;
                });
    }

    public void queryCorrectionList() {
        LogUtils.info(log, "获取测评对象结果修正信息...");
        LogUtils.record(log, "请求数据，systemId：{},layerTargetId:{}", this.currentSystemId, currentLayerTarget.getCode());
        CompletableFuture.supplyAsync(() -> this.resultCorrectionService.findResultCorrectionByLayerTarget(this.currentSystemId,
                        currentLayerTarget.getCode(), false), this.executor)
                .thenAccept(res -> Platform.runLater(() -> {
                    if (res.isSuccess()) {
                        this.evalCorrectionBox.setVisible(true);
                        this.emptyPane.setVisible(false);
                        var data = res.getData().stream()
                                .map(ResultCorrectionViewMapper.INSTANCE::toVO)
                                .toList();
                        this.sheetView.loadContent(data);
                    }else{
                        this.evalCorrectionBox.setVisible(false);
                        this.emptyPane.setVisible(true);
                        this.emptyLabel.setText(res.getMsg());
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("获取测评对象结果修正信息出错!", ex);
                    MessageDialog.builder()
                            .withContainer(this.page)
                            .withType(MessageType.FAIL)
                            .withMessage("加载数据表内容失败！")
                            .build().show();
                    return null;
                });
    }

    private void batchSaveCorrection(boolean realTime,boolean finish) {
        List<ResultCorrectionDTO> resultCorrectionDTOS = this.sheetView.getModifyData().stream()
                .filter(ResultCorrectionVO::isChange)
                .map(ResultCorrectionViewMapper.INSTANCE::toDTO)
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(resultCorrectionDTOS)) {
            setCorrectionFinishState(realTime,finish);
            return;
        }
        LogUtils.info(log, "批量保存测评对象结果修正信息...");
        LogUtils.record(log, "请求数据:{}", resultCorrectionDTOS);
        //未保存的数据进行批量保存
        CompletableFuture.supplyAsync(() -> this.resultCorrectionService.batchSaveResultCorrection(resultCorrectionDTOS),this.executor)
                .thenAccept(res -> Platform.runLater(() -> {
                    if (!res.isSuccess()) {
                        if(realTime){
                            log.error("即时保存测评对象结果修正信息失败：{}",res.getMsg());
                        }else{
                            AppUtils.showMessageDialog(res.getMsg(),MessageType.FAIL,this.page);
                        }
                    } else {
                        queryCorrectionList();
                        setCorrectionFinishState(realTime,finish);
                        ControlUtils.refreshScoreInfo(this.currentSystemId);
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("批量保存测评对象结果修正信息出错!", ex);
                    return null;
                });
    }

    private void setCorrectionFinishState(boolean realTime,boolean finishSave) {
        FinishState state = finishSave ? FinishState.FINISH : FinishState.INCOMPLETE;
        LogUtils.info(log, "设置风险分析完成进度...");
        LogUtils.record(log, "请求数据，systemId：{},targetId:{},state：{}", this.currentSystemId,
                currentLayerTarget.getCode(), state);
        CompletableFuture.supplyAsync(() -> resultCorrectionService.setFinishStateByLayerTarget(this.currentSystemId
                        , currentLayerTarget.getCode(), state),this.executor)
                .thenAccept(res -> Platform.runLater(() -> {
                    if (res.isSuccess()) {
                        if(!realTime){
                            AppUtils.showMessageDialog("保存成功",MessageType.SUCCESS,this.page);
                        }
                        refreshFinishState(state);
                    } else {
                        if(realTime){
                            log.error("即时设置风险分析完成进度失败：{}",res.getMsg());
                        }else{
                            AppUtils.showMessageDialog(res.getMsg(),MessageType.FAIL,this.page);
                        }
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("设置风险分析完成进度出错!", ex);
                    return null;
                });
    }

    private void refreshFinishState(FinishState state){
        var correctionView = AppStore.getEvaluationView(this.currentSystemId, ResultCorrectionView.class);
        if(correctionView.getController() instanceof ResultCorrectionController controller){
            controller.setLayerFinishState(this.currentLayerTarget, state);
        }
    }
}